package com.definesys.smecrailtransit.service.LogService;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.definesys.smecrailtransit.utils.ThreadPoolExecutorUtil;
import com.hwangjr.rxbus.SmecRxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;

/**
 * Created by xupeizuo on 2017/3/2.
 */

public final class LogService extends Service implements LogSericeContract{

    public static final String SERVICE_ACTION="com.smec.install.shakedown.sericve.LogService";

    private LogServicePresenter logServicePresenter;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        SmecRxBus.get().register(this);
        super.onCreate();
        Log.e("当前线程",Thread.currentThread().getName());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        SmecRxBus.get().unregister(this);
    }

    public LogServicePresenter getPresneter(){
        return new LogServicePresenter(this);
    }

    /**
     * 操作异常信息
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(SERVICE_ACTION)
            }
    )
    public void operatorExceptionMsg(Object o){

        Log.e("wrer","weweweq");

        if(logServicePresenter == null ){
            logServicePresenter=getPresneter();
        }

        final ExceptionDto exceptionDto=getDataFromRealm();

        if(exceptionDto !=null){
            ThreadPoolExecutorUtil.getFixedThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    uploadDataToServer(exceptionDto);
                }
            });
        }else {
            Log.e("&&&&","现在没有异常信息");
        }

    }

    /**
     * 上传数据至服务器
     * @param exceptionDto
     */
    public void uploadDataToServer(ExceptionDto exceptionDto){

        logServicePresenter.uploadDataToServer(exceptionDto);
    }

    /**
     * 获取本地异常信息
     * @return
     */
    public ExceptionDto getDataFromRealm(){

        return logServicePresenter.getDataFromRealm();
    }

    /**
     * 从本地删除上次的异常信息
     */
    public void deteleDataFromRealm(ExceptionDto exceptionDto){

    }
}
